package freespiritsocial.io.user.viewmodel

import freespiritsocial.io.user.data.model.bean.UserInfo
import freespiritsocial.io.user.viewmodel.delegates.UserInfoViewModel
import kotlinx.coroutines.flow.*
import me.hgj.jetpackmvvm.base.viewmodel.BaseViewModel
import me.hgj.jetpackmvvm.callback.livedata.StringLiveData
import me.hgj.jetpackmvvm.ext.util.loge

class SearchFriendViewModel: UserInfoViewModel() {

    val allData = arrayListOf<UserInfo>()
    val searchText = StringLiveData()
    private val _stateFlow = MutableStateFlow("")
    val searchResultNetWork =
        // 避免在单位时间内，快输入造成大量的请求
        _stateFlow.debounce(100)
            .flatMapLatest {
                if (it.isEmpty())
                    allData.asFlow()
                else
                    allData.filter { user -> user.name?.contains(it,true) == true }.asFlow()
            }.catch {
                this.toString().loge("catch")
            }

    fun search() {
        _stateFlow.value = searchText.value
    }
}